package com.matriq.cloudmanager;

import net.lgpage.activity.BaseActivity;

public class PlayerActivity extends BaseActivity {
	/*long maxLength;
	int curTime;
	SeekBar sb_progress;
	SeekBarChangeThread seekbarchangethread;
	boolean seekbarcanchange;
	private static String TAG = "PlayonlineActivity";
	private static final int VIDEO_TIME_CHANGE = 1;
	private static final int BT_PAUSE_IMAGE_CHANGE = 2;
	Handler handler;
	SurfaceHolder holder;
	MediaPlayer player;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (!LibsChecker.checkVitamioLibs(this))
			return;
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
		setContentView(R.layout.ac_player);
		setViews();
		setEvents();
		loadData();
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
			fm.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		}else{
			fm.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(this, 250f)));
		}
		super.onConfigurationChanged(newConfig);
	}
	ImageButton ib_back;
	TextView tv_maxtime;
	ImageButton ib_play;
	ImageButton ib_download;
	TextView tv_title;
	ToggleButton tb_loop;
	TextView tv_curtime;
	ViewGroup fm_controller;
	FrameLayout fm;
	LinearLayout ll_comment;
	ImageView iv[] = new ImageView[3];
	TextView tv_playtime;
	ImageView iv_share;
	TextView tv[] = new TextView[8];
	ViewGroup ll_extra;
	SurfaceView sv;
	TextView tv_sharenum;
	EditText et;

	private void setViews() {
		ib_back = (ImageButton) this.findViewById(R.id.ib_back);
		tv_maxtime = (TextView) this.findViewById(R.id.tv_maxtime);
		sb_progress = (SeekBar) this.findViewById(R.id.sb_progress);
		ib_play = (ImageButton) this.findViewById(R.id.ib_play);
		ib_download = (ImageButton) this.findViewById(R.id.ib_download);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		tb_loop = (ToggleButton) this.findViewById(R.id.tb_loop);
		tv_curtime = (TextView) this.findViewById(R.id.tv_curtime);
		
		fm_controller = (ViewGroup) this.findViewById(R.id.fm_controller);
		fm = (FrameLayout) this.findViewById(R.id.fm);
		ll_comment = (LinearLayout) this.findViewById(R.id.ll_comment);
		iv[0] = (ImageView) this.findViewById(R.id.iv0);
		iv[1] = (ImageView) this.findViewById(R.id.iv1);
		iv[2] = (ImageView) this.findViewById(R.id.iv2);
		tv_playtime = (TextView) this.findViewById(R.id.tv_playtime);
		iv_share = (ImageView) this.findViewById(R.id.iv_share);
		tv[0] = (TextView) this.findViewById(R.id.tv0);
		tv[1] = (TextView) this.findViewById(R.id.tv1);
		tv[2] = (TextView) this.findViewById(R.id.tv2);
		tv[3] = (TextView) this.findViewById(R.id.tv3);
		tv[4] = (TextView) this.findViewById(R.id.tv4);
		tv[5] = (TextView) this.findViewById(R.id.tv5);
		tv[6] = (TextView) this.findViewById(R.id.tv6);
		tv[7] = (TextView) this.findViewById(R.id.tv7);
		ll_extra = (ViewGroup) this.findViewById(R.id.ll_extra);
		sv = (SurfaceView) this.findViewById(R.id.sv);
		tv_sharenum = (TextView) this.findViewById(R.id.tv_sharenum);
		et = (EditText) this.findViewById(R.id.et);
	}


	Object copyObj;

	public boolean checkEts() {
		if (copyObj == null) {
			copyObj = new Object();
		}

		String str_et = et.getEditableText().toString();

		if (StringChecker.isNull(str_et)) {
			setError("不能为空", et);
			return false;
		}

		return true;
	}

	ObjTask objTask;

	public void putObj() {
		if (objTask != null) {
			objTask.cancel(true);
		}
		objTask = new ObjTask(this);
		objTask.execute();
	}

	private class ObjTask extends ExceptionAsyncTask<Object> {

		public ObjTask(Context context) {
			super(context);
		}

		@Override
		public Object doInBackgroundX(String... params) throws Exception {
			return null;
		}

		@Override
		public void onPostExecuteX(Object result) {
			if (result == null) {
				return;
			} else {
				// Snackbar.make(this, "成功", 1).show();
			}
		}
	}


	
	
Runnable closeRunnable = new Runnable() {
		
		@Override
		public void run() {
			fm_controller.setVisibility(View.INVISIBLE);
			handler.removeCallbacks(closeRunnable);
		}
	};
	private void closeDelay(){
		handler.removeCallbacks(closeRunnable);
		handler.postDelayed(closeRunnable, 3000);
	}
	
	 * 1.赋值控件引用 2.控件事件设置
	 
	public void setEvents() {
		// 点击事件
		ib_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (player != null) {
					if (player.isPlaying()) {
						player.pause();
					} else {
						player.start();
					}
					handler.sendEmptyMessage(BT_PAUSE_IMAGE_CHANGE);
					closeDelay();
				}
			}
		});
		tb_loop.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				Log.e(TAG, "isCheck" + isChecked);
				if (player != null) {
					player.setLooping(isChecked);
				}
				closeDelay();
			}
		});
		// 点击事件
		ib_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getActivity().finish();
			}
		});
		// 点击事件
		sv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fm_controller.setVisibility(View.VISIBLE);
				closeDelay();
			}
		});
		// 点击事件
		fm_controller.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fm_controller.setVisibility(View.GONE);
				handler.removeCallbacks(closeRunnable);
			}
		});
		handler = new PlayHandler();
		holder = sv.getHolder();
		holder.setFormat(PixelFormat.RGBA_8888); 
		//holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		//ib_collect.setVisibility(View.GONE);
		ib_download.setVisibility(View.GONE);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onDestroy() {
		if (seekbarchangethread != null) {
			seekbarchangethread.close();
		}
		//doClean();
		if(et!=null)
		et.clearFocus();
		super.onDestroy();
	}

	int  position;
	String url;
	CourseInfo obj;
	//String data;
	private void loadData() {
		url = getIntent().getStringExtra("url");
		if(TextUtils.isEmpty(url)){
			obj = (CourseInfo) intentGetObj(CourseInfo.class);
			if(obj!=null){
				url = obj.getUrl();
			}else
			url = "http://test123-10012456.video.myqcloud.com/sp2.mp4";
			//url = "http://192.168.1.7:8080/mi1401011.wmv";
		}
		
		holder.addCallback(new SurfaceCallback());
	}
	private static final int NOTIFICATION_FLAG = 1;  
	@SuppressLint("NewApi")
	@Override
	public void onBackPressed() {
		if(!player.isPlaying()){
			doClean();
			finish();
			return;
		}
		NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
		Intent intent = new Intent(this,PlayerActivity.class);  
		if(obj != null){
			intent.putExtra("obj", GsonTool.getGson().toJson(obj));
		}else{
			intent.putExtra("url",url);
		}
        PendingIntent contentIntent = PendingIntent.getActivity(this, 1,  
                intent, 0);  
        NotificationCompat.Builder b = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)  
        .setTicker("TickerText:" + "您有新短消息，请注意查收！")  
        .setContentTitle("Notification Title")  
        .setContentText("This is the notification message") 
       // .setTicker("TickerText:" + "您有新短消息，请注意查收！")  
        .setContentIntent(contentIntent);
        Notification no = b.build();
       // no.flags|=Notification.FLAG_AUTO_CANCEL;
        no.contentView = new RemoteViews(getPackageName(), R.layout.fm_controller);
        if(obj!=null){
        	no.contentView.setTextViewText(R.id.tv_title, obj.getTitle());
        }
       Intent si =  DownloadService.getStopIntent(this, url);
       //si.putExtra("RemoteViews",  no.contentView );
        PendingIntent stopIntent = PendingIntent.getService(this, 1,  
        		si, 0);  
        no.contentView.setOnClickPendingIntent(R.id.ib_play, stopIntent);
        no.contentView.setTextViewText(R.id.tv_maxtime, TimeUtil.durationtoMMss((int) player.getDuration()));
        no.flags |=Notification.FLAG_AUTO_CANCEL;
        manager.notify(NOTIFICATION_FLAG, no);  
		player.setDisplay(null);
		position = (int) player.getCurrentPosition();
		//doClean();
		Intent it = new Intent(this, PlayerService.class);
		startService(it);
		bindService(it, new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName name) {
				
			}
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				MyBinder b = (MyBinder) service;
				b.playBackground(player);
				player = null;
				finish();
				unbindService(this);
			}
		}, Context.BIND_AUTO_CREATE);
		
		//super.onBackPressed();
	}
	public void doClean(){
		if (player != null) {
			player.stop();
			player.release();
			player = null;
		}
	}
	public void upVoice() {
		// 音量控制,初始化定义
		AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		// 最大音量
		int maxVolume = mAudioManager
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		// 当前音量
		int currentVolume = mAudioManager
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		if (currentVolume < maxVolume) {
			currentVolume++;
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
					currentVolume, 0); // tempVolume:音量绝对值
		}
	}

	public void downVoice() {
		// 音量控制,初始化定义
		AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		// 最大音量
		int maxVolume = mAudioManager
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		// 当前音量
		int currentVolume = mAudioManager
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		if (currentVolume > 0) {
			currentVolume--;
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
					currentVolume, 0); // tempVolume:音量绝对值
		}
	}
	
	 * 在positon处播放
	 
	public void play(String path, final int position) {
		try {
			if (player != null) {
				player.stop();
				player.release();
				player = null;
			}
			player = new MediaPlayer(getActivity());
			player.setDataSource(path);
			//player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			player.setDisplay(holder);
			player.prepareAsync();
			player.setOnPreparedListener(new OnPreparedListener() {

				public void onPrepared(MediaPlayer mp) {
					player.start();
					player.setLooping(tb_loop.isChecked());
					player.seekTo(position);
					maxLength = mp.getDuration();
					sb_progress.setMax((int) mp.getDuration());
					sb_progress.setOnSeekBarChangeListener(new ScheduleSeekBarChangeListener());
					seekbarchangethread = new SeekBarChangeThread();
					seekbarchangethread.start();
					handler.sendEmptyMessage(BT_PAUSE_IMAGE_CHANGE);
				}
			});

		} catch (Exception e) {
			System.out.println("error ");
			e.printStackTrace();
		}
	}

	
	 * 进度条被拖动改变播放进度
	 
	private class ScheduleSeekBarChangeListener implements
			OnSeekBarChangeListener {
		public void onProgressChanged(SeekBar arg0, int progress,
				boolean fromUser) {
			if (fromUser) {
				if (player != null){
					if(progress<player.getCurrentPosition()){
						player.seekTo(progress);
					}else{
						player.seekTo(progress);
						//sb_progress.setProgress((int) player.getCurrentPosition());
					}
				}
			}
		}

		public void onStartTrackingTouch(SeekBar arg0) {
			seekbarcanchange = true;
		}

		public void onStopTrackingTouch(SeekBar arg0) {
			seekbarcanchange = false;
		}
	}

	private final class SurfaceCallback implements Callback {
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
		}

		public void surfaceCreated(final SurfaceHolder holder) {
			Intent it = new Intent();
			it.setClass(getActivity(), PlayerService.class);
			bindService(it, new ServiceConnection() {
				
				@Override
				public void onServiceDisconnected(ComponentName name) {
					
				}
				
				@Override
				public void onServiceConnected(ComponentName name, IBinder service) {
					MyBinder binder = (MyBinder) service;
					player = binder.playForeground();
					Log.e("haha", "onServiceConnected");
					if(player==null){
						Log.e("haha", "?1");
						play(url, position);
					}else{
						Log.e("haha", "?2");
						player.setDisplay(holder);
						maxLength = player.getDuration();
						sb_progress.setMax((int) player.getDuration());
						sb_progress.setOnSeekBarChangeListener(new ScheduleSeekBarChangeListener());
						seekbarchangethread = new SeekBarChangeThread();
						seekbarchangethread.start();
						handler.sendEmptyMessage(BT_PAUSE_IMAGE_CHANGE);
					}
					unbindService(this);
				}
			}, Context.BIND_AUTO_CREATE);
				
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			if (player != null) {
				if (player.isPlaying()) {
					player.stop();
				}
			}
		}
	}

	
	 * 实时更新进度条的线程 拖动进度时会使线程暂停 拖动结束后继续，scheduleSeekBar的onprogresschange方法
	 
	private class SeekBarChangeThread extends Thread {
		private boolean open;

		public SeekBarChangeThread() {
			open = true;
		}

		public void close() {
			open = false;
		}

		public void run() {
			seekbarcanchange = false;
			while (open) {
				if (player != null) {
					if (player.isPlaying()) {
						if (!seekbarcanchange) {
							try {
								sb_progress.setProgress((int) player.getCurrentPosition());
							} catch (Exception e) {
							}
							curTime = (int) player.getCurrentPosition();
							handler.sendEmptyMessage(VIDEO_TIME_CHANGE);
						}
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}

		}
	}

	class PlayHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case VIDEO_TIME_CHANGE:
				tv_curtime.setText(TimeUtil.durationtoMMss(curTime));
				tv_maxtime.setText(TimeUtil.durationtoMMss((int) maxLength));
				break;
			case BT_PAUSE_IMAGE_CHANGE:
				if (player != null) {
					if (player.isPlaying()) {
						ib_play.setBackgroundResource(R.drawable.videoplayer_pause_selector);
					} else {
						ib_play.setBackgroundResource(R.drawable.videoplayer_play_selector);
					}
				}
				break;
			default:
				break;
			}
		}
	}*/

}